var screen = {
   
   canvas: {
      obj: null
   },
   
   ctx: {
      obj: null,
      width: 0,
      height: 0
   },
   
   img: {
      obj: null
   }
   
};


var sampleImg = new Image();
sampleImg.src = '/sample-img/pancakation (7).JPG';

sampleImg.onload = function()
{
   init();
};

function log(msg)
{
   document.getElementById('dialog').innerHTML += msg + '<br/>';
}


function getImgDimensions()
{
   var w = screen.canvas.obj.width - screen.img.obj.width < 0 ?
      screen.canvas.obj.width : screen.img.obj.width;
   
   var h = screen.canvas.obj.height - screen.img.obj.height < 0 ?
      screen.canvas.obj.height : screen.img.obj.height;
   
   return {width: w, height: h};
}

function init()
{
   screen.canvas.obj = document.getElementById('screen');

   screen.img.obj = sampleImg;
   
   screen.ctx.obj = screen.canvas.obj.getContext('2d');
   screen.ctx.width = getImgDimensions().width;
   screen.ctx.height = getImgDimensions().height;
   
   screen.ctx.obj.drawImage(screen.img.obj, 0, 0);
   
   log('Image loaded.');
   log('Element widths: img: ' + 
      screen.img.obj.width + 'x' + screen.img.obj.height + ', canvas: ' + 
      screen.ctx.width + 'x' + screen.ctx.height);
}


function action_grayscale()
{
   log('Grayscalling...');
   
   var imgData = screen.ctx.obj.getImageData(0, 0, screen.img.obj.width, screen.img.obj.height);
   
   var len = imgData.data.length;
   
   for(var i = 0; i < len; i += 4)
   {
	var avg = (imgData.data[i] + imgData.data[i + 1] + imgData.data[i + 2]) / 3;
      imgData.data[i] = avg;
      imgData.data[i + 1] = avg - 2;
      imgData.data[i + 2] = avg - 2;
   }
   
   screen.ctx.obj.putImageData(imgData, 0, 0);
   
   log('Grayscalling...');
}


function action_histogram()
{
   log('histoitup');
}

function action_reset()
{
   log('Resetting...');
   
   screen.ctx.obj.clearRect(0, 0, screen.canvas.obj.width, screen.canvas.obj.height);
   screen.ctx.obj.drawImage(screen.img.obj, 0, 0);
   
   log('Canvas reset');
}